package edu.tces482.plms.util;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Logger;

public class ByteQueue {
	
	private static final Logger LOGGER = Logger.getLogger(ByteQueue.class.getName());
	
	private LinkedBlockingQueue<byte []> dataBufferQueue = new LinkedBlockingQueue<byte[]>();
	private byte [] currentBuffer = null;
	private int position = 0;
	
	public boolean add(final byte data) {
		return dataBufferQueue.add(new byte [] { data });
	}
	
	public boolean add(final byte [] data) {
		return dataBufferQueue.add(data);
	}
	
	public byte take() {
		if (currentBuffer == null || position == currentBuffer.length) {
			currentBuffer = null;									// Discard old data buffer
			position = 0;											// Reset position
			try {
				currentBuffer = dataBufferQueue.take();				// Get next data buffer.
			} catch (InterruptedException e) {
				// Do nothing
			}
			LOGGER.finest("Retrieved next data buffer, size: " + currentBuffer.length);
		}
		return currentBuffer[position++];
	}
	
	public int size() {
		return dataBufferQueue.size();
	}

}
